<template>
	<view>
		<view class="edgeInsetTop"></view>
		<form @submit="formSubmit">
			<view class="cu-list menu solid-bottom">
				<view class="cu-item" style="min-height:150rpx;" @tap="handleImage('avatar')">
					<view class="content">
						<text style="font-size: 30rpx;">店铺头像</text>
					</view>
					<view class="action">
						<image v-if="avatar" :src="avatar" class="radius-bock" style="width: 120rpx;height:120rpx;">
						</image>
						<view v-else
							class="text-gray flex flex-direction bg-gray justify-center align-center radius-bock"
							style="width: 120rpx;height:120rpx;">
							<text class="wlIcon-tianjia"></text>
							<view class="margin-top-xs text-xs">添加图片</view>
						</view>
					</view>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">店铺名称</view>
				<input placeholder="请输入店铺名称" name="shopname"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">店铺简介</view>
				<input placeholder="请输入店铺简介" name="content"></input>
			</view>

			<view class="cu-form-group">
				<view class="title">店铺类型</view>
				<picker @change="typeChange" :value="index" range-key="name" :range="typeArr">
					<view class="uni-input" style="color: grey;">
						{{typeArr[index].name}}
					</view>
				</picker>
				<text class="wlIcon-fanhui2"></text>
			</view>

			<view class="cu-form-group">
				<view class="title">店铺位置</view>
				<input :placeholder="address" name="address" @tap="chooseLocation"></input>
				<text class="wlIcon-fanhui2"></text>
			</view>

			<view class="cu-form-group">
				<view class="title">营业起始时间</view>
				<picker mode="time" :value="starttime" start="" end="" @change="startTimeChange">
					<view class="uni-input">{{starttime}}</view>
				</picker>
				<text class="wlIcon-fanhui2"></text>
			</view>
			<view class="cu-form-group">
				<view class="title">营业结束时间</view>
				<picker mode="time" :value="endtime" start="" end="" @change="endTimeChange">
					<view class="uni-input">{{endtime}}</view>
				</picker>
				<text class="wlIcon-fanhui2"></text>
			</view>

			<view class="cu-form-group">
				<view class="title">上传营业执照</view>
			</view>
			<view class="upload">
				<view class="upload-box flex justify-center align-center">
					<view v-if="card1" class="grid">
						<view class="upload-item flex-1 radius" @tap="handlePreview('card1')" style="width:500rpx">
							<image :src="card1" style="height: 240rpx; width: 100%;"></image>
						</view>
						<view class="tag" @tap="handleDelImage('card1')">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>
					<view v-else class="upload-item radius" @tap="handleImage('card1')" style="width:500rpx">
						<view class="flex justify-center align-center">
							<text class="wlIcon-tianjia flex align-center text-gray" style="font-size: 40rpx;"></text>
						</view>
						<view class="text-xs text-gray">上传企业法人/个体工商户营业执照</view>
					</view>
				</view>
			</view>

			<view class="cu-form-group" v-if="card1 && isCard1">
				<view class="title">证件号码</view>
				<input placeholder="统一社会信用代码" name="biz_code" v-model="biz_code"></input>
			</view>

			<view class="cu-form-group" v-if="card1 && isCard1">
				<view class="title">企业名称</view>
				<input placeholder="执照名称" name="biz_company" v-model="biz_company"></input>
			</view>

			<view class="cu-form-group" v-if="card1 && isCard1">
				<view class="title">法人姓名</view>
				<input placeholder="法定代表人姓名" name="biz_name" v-model="biz_name"></input>
			</view>

			<view class="cu-form-group">
				<view class="title">上传法人身份证明</view>
			</view>

			<view class="upload">
				<view class="upload-box flex justify-around align-center">
					<view v-if="card2" class="grid">
						<view class="upload-item flex-1 radius" @tap="handlePreview('card2')" style="width:320rpx">
							<image :src="card2" style="height: 200rpx; width: 100%;"></image>
						</view>
						<view class="tag" @tap="handleDelImage('card2')">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>
					<view v-else class="upload-item flex-1 radius" @tap="handleImage('card2')" style="width:320rpx">
						<view class="flex justify-around align-center">
							<text class="wlIcon-tianjia flex align-center text-gray" style="font-size: 40rpx;"></text>
						</view>
						<view class="text-xs text-gray">上传身份证人像面</view>
					</view>



					<view v-if="card3" class="grid">
						<view class="upload-item flex-1 radius" @tap="handlePreview('card3')" style="width:320rpx">
							<image :src="card3" style="height: 200rpx;width: 100%;"></image>
						</view>
						<view class="tag" @tap="handleDelImage('card3')">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>
					<view v-else class="upload-item flex-1 radius" @tap="handleImage('card3')" style="width:320rpx">
						<view class="flex justify-around align-center">
							<text class="wlIcon-tianjia flex align-center text-gray" style="font-size: 40rpx;"></text>
						</view>
						<view class="text-xs text-gray">上传身份证头徽面</view>
					</view>
				</view>
			</view>

			<view class="cu-form-group" v-if="card2 && card3">
				<view class="title">证件姓名</view>
				<input placeholder="法人姓名" name="name" v-model="name"></input>
			</view>

			<view class="cu-form-group" v-if="card2 && card3">
				<view class="title">身份证号</view>
				<input placeholder="法人身份证号" name="id_card" v-model="id_card"></input>
			</view>


			<view class="safeAreaBottom"></view>
			<view class="wanlfind-add-container__foot">
				<view class="cu-bar tabbar foot flex flex-direction bg-white align-center">
					<view class="padding-lr-bj" style="width: 100%;">
						<button form-type="submit" class="wanl-bg-redorange">提交审核</button>
					</view>
				</view>
			</view>
		</form>


	</view>
</template>

<script>
	import graceChecker from '@/common/graceChecker';
	import {
		mapState
	} from 'vuex';
	import qqmapwx from "@/static/js/qqmap-wx-jssdk.min.js"
	export default {
		computed: {
			...mapState(['user'])
		},
		data() {
			return {
				typeArr: ['美食', '外卖', '甜品饮料', '休闲娱乐'],
				index: 0,
				shopname: '',
				content: '',
				mobile: '',
				type: 1, //1美食 2外卖 3甜品饮料 4休闲娱乐
				longitude: '', //经度
				latitude: '', //维度
				province: '',
				city: '',
				area: '',
				address: '定位中..', //地名
				avatar: '', //店铺图片
				card1: '', //营业执照
				card2: '',
				card3: '',
				biz_code: '', //营业执照代码
				biz_company: '', //公司名称,
				biz_name: '', //法人
				name: '',
				id_card: '',
				cname: '', //复制
				cIDcard: '', //复制
				isCard1: false,
				biz_time: '', //营业时间
				starttime: '00:00',
				endtime: '00:00'
			}
		},
		onLoad() {
			//中央总线重新赋值Data						
			this.getAddress();
			this.getChooseTypeList();
		},
		methods: {
			//店铺类型列表

			getChooseTypeList() {
				uni.request({
					url: '/wanlshop/bussinfo/getBussinfoList',
					success: (res) => {
						if (res.res.code == 1) {
							this.typeArr = res.res.data.map(item => {
								return {
									name: item.name,
									id: item.id
								}
							})

						}
					}
				})
			},


			//营业时间
			startTimeChange: function(e) {
				this.starttime = e.detail.value
			},
			endTimeChange: function(e) {
				this.endtime = e.detail.value
			},
			//选择定位
			chooseLocation() {
				let _this = this
				uni.chooseLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					success: function(res) {
						console.log("res=>" + JSON.stringify(res));
						_this.address = res.name
						/**
						 * res=>{"address":"湖北省襄阳市樊城区新华路","latitude":32.05634,"name":"樊城区万达铁路二院2区(新华路北150米)","longitude":112.145615,"errMsg":"chooseLocation:ok"}
						 */
						let address = res.address;
						if (address && address.indexOf('省') > 0) {
							let str = address.split("省");
							if (str) {
								_this.province = str[0] + "省";
								if (str[1].indexOf('市') > 0) {
									let str2 = str[1].split("市");
									_this.city = str2[0] + "市";
									_this.area = str2[1];
								}

							}
						}

					}
				});
			},
			//选择店铺类型
			typeChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.type = this.typeArr[e.detail.value]["id"];
				this.index = e.detail.value;
			},
			formSubmit: function(e) {
				//定义表单规则

				let rule = [{
						name: 'shopname',
						checkType: 'string',
						checkRule: '3,32',
						errorMsg: '店铺名称，至少3-32字符'
					},
					{
						name: 'content',
						checkType: 'string',
						checkRule: '3,100',
						errorMsg: '店铺简介，至少3-100字符'
					}
				];
				//进行表单检查
				let formData = e.detail.value;
				formData.type = this.type
				formData.avatar = this.avatar
				formData.card1 = this.card1
				formData.card2 = this.card2
				formData.card3 = this.card3
				formData.longitude = this.longitude
				formData.latitude = this.latitude
				formData.province = this.province
				formData.city = this.city
				formData.area = this.area
				formData.address = this.address

				formData.biz_code = this.biz_code
				formData.biz_company = this.biz_company
				formData.biz_name = this.biz_name
				formData.name = this.name
				formData.id_card = this.id_card
				formData.biz_time = this.starttime + '-' + this.endtime


				// formData.longitude = 114.224362
				// formData.latitude = 30.519978
				// formData.province = "湖北省"
				// formData.city = "武汉市"
				// formData.area = "汉阳区"
				// formData.address = "光明上海府邸"

				if (this.avatar === '') {
					this.$wanlshop.msg('请上传店铺图片~');
					return
				}
				let checkRes = graceChecker.check(formData, rule);
				// 表单验证
				if (checkRes) {
					if (this.card1 === '') {
						this.$wanlshop.msg('请上传营业执照~');
						return
					}
					if (this.card2 === '' || this.card3 === '') {
						this.$wanlshop.msg('请上传身份证~');
						return
					}

					if (this.biz_code === '' || this.biz_company === '') {
						this.$wanlshop.msg('请完善企业信息~');
						return
					}
					if (this.name === '' || this.id_card === '') {
						this.$wanlshop.msg('请完善身份信息~');
						return
					}
					// if(this.province=== '' || this.city === '' || this.area === ''){
					// 	this.$wanlshop.msg('当前地址获取失败，请重新获取地址~');
					// 	return
					// }


					uni.request({
						url: '/wanlshop/passport/biz_auth',
						method: 'POST',
						data: formData,
						success: res => {
							this.$wanlshop.msg('提交成功,请等待审核');
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/user'
								})
							}, 1000)
						}
					});
				} else {
					this.$wanlshop.msg(graceChecker.error);
				}
			},


			//图片预览
			handlePreview(type) {
				console.log(this.card2)
				uni.previewImage({
					urls: this.card2,
					current: this.card2,
				})
			},

			//删除图片
			handleDelImage(type) {
				switch (type) {
					case 'card1':
						this.card1 = '';
						break;
					case 'card2':
						this.card2 = '';
						break;
					case 'card3':
						this.card3 = '';
						break;
				}
			},
			//选择图片
			handleImage(type) {
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						//console.log(res)
						if (res.tempFilePaths) {
							res.tempFilePaths.map((item, index) => {
								// 延迟触发一下
								uni.request({
									url: '/wanlshop/common/uploadData',
									success: updata => {
										uni.getImageInfo({
											src: res.tempFilePaths[0],
											success: image => {
												uni.uploadFile({
													url: updata.data
														.uploadurl,
													filePath: image
														.path,
													name: 'file',
													formData: updata
														.data
														.storage ==
														'local' ?
														null : updata
														.data
														.multipart,
													success: data => {
														let src =
															'https://adminshop.12sxb.cn/' +
															JSON
															.parse(
																data
																.data
															)
															.data
															.url
														//let src = 'http://renrenshop.test' + JSON.parse(data.data).data.url
														if (type ==
															'avatar'
														) {
															this.avatar =
																src
														}
														if (type ==
															'card1'
														) {
															this.card1 =
																src
															this.toBiz(
																src
															)
														}

														if (type ===
															'card2'
														) {
															this.card2 =
																src
															this.toOcr(
																type,
																src
															)
														}
														if (type ===
															'card3'
														) {
															this.card3 =
																src
															this.toOcr(
																type,
																src
															)
														}
													},
													fail: error => {
														uni.showToast({
															title: JSON
																.parse(
																	error
																	.data
																)
																.msg,
															icon: 'error',
															position: true
														});
													}
												});
											}
										});


									}
								});
							})
						}
					}
				});
			},
			//验证营业执照
			toBiz(image) {
				uni.showLoading({
					title: '营业执照识别中',
					mask: true
				})
				let token = uni.getStorageSync("wanlshop:user").token
				uni.request({
					url: `https://adminshop.12sxb.cn/api/wanlshop/passport/biz_ocr?image=${image}`,
					method: 'GET',
					header: {
						'token': token
					},
					success: res => {
						uni.hideLoading()
						if (res.res.msg === 'ok') {
							if (res.data.RegNum && res.data.Name) {
								this.biz_code = res.data.RegNum
								this.biz_company = res.data.Name
								this.biz_name = res.data.Person
								this.isCard1 = true
								console.log(this.biz_code)
							} else {
								this.$wanlshop.msg('营业执照识别错误，请重新上传~')
								this.card1 = ''
							}
						} else {
							this.$wanlshop.msg(res.res.data)
							this.card1 = ''
						}
					}
				})
			},


			//验证身份
			toOcr(type, image) {
				uni.showLoading({
					title: '身份证识别中',
					mask: true
				})
				//获取token
				let token = uni.getStorageSync("wanlshop:user").token
				console.log(token)
				uni.request({
					url: `https://adminshop.12sxb.cn/api/wanlshop/passport/ocr?image=${image}`,
					method: 'GET',
					header: {
						'token': token
					},
					success: res => {
						uni.hideLoading()
						if (res.res.msg === 'ok') {
							if (type === 'card2') {
								if (res.data.Name && res.data.IdNum) {
									this.cname = res.data.Name
									this.cIDcard = res.data.IdNum
								} else {
									this.$wanlshop.msg('身份证正面识别错误，请重新上传~')
									this.card2 = ''
								}
							}
							if (type === 'card3' && this.cname && this.cIDcard) {
								if (res.data.ValidDate) {
									this.name = this.cname
									this.id_card = this.cIDcard
								} else {
									this.$wanlshop.msg('身份证反面识别错误，请重新上传~')
									this.card3 = ''
								}
							}
						} else {
							this.$wanlshop.msg(res.res.data)
							if (type === 'card2') {
								this.card2 = ''
							}
							if (type === 'card3') {
								this.card3 = ''
							}
						}
					}
				})
			},

			//获取定位
			getAddress() {
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					isHighAccuracy: true,
					altitude: true,
					success: res => {
						console.log("res=>" + JSON.stringify(res));
						this.longitude = res.longitude;
						this.latitude = res.latitude;
						let _addressData = uni.getStorageSync('addressData'); /*全局缓存相关的数据*/
						if (_addressData) {
							let addressData = JSON.parse(_addressData);
							if (addressData.province) this.province = addressData.province;
							if (addressData.city) this.city = addressData.city;
							if (addressData.district) this.area = addressData.district;
							console.log("this.province = " + this.province);
							console.log("this.city = " + this.city);
							console.log("this.area = " + this.area);
						} else {
							//换腾讯地图


							qqmapsdk.reverseGeocoder({
								location: {
									latitude,
									longitude
								},
								success: function(res) {

									let address = res.result.address_component;

									const addressData = {
										address: address,
										atitude: latitude,
										longitude: longitude
									}
									address.longitude = longitude;
									address.latitude = latitude;

									uni.setStorageSync('addressData', JSON.stringify(
										addressData)); /*全局缓存相关的数据*/



								},
								fail: function(error) {
									console.error(error);
								},
								complete: function(res) {
									console.log(res);
								}
							})





							// 以高德地图API为例
							// 		  const amapKey = '817dcdcf5e5a3c606f6f13d76d563e8a';
							// 		  const url = `https://restapi.amap.com/v3/geocode/regeo?key=${amapKey}&location=${this.longitude},${this.latitude}`;
							// 		  uni.request({
							// 				url: url,
							// 				success: (response) => {
							// 					  const address = response.data.regeocode.addressComponent;
							// 					  console.log("App address =>" + JSON.stringify(address)); 
							// 					  const addressData = {
							// 						address:address,
							// 						latitude:latitude,
							// 						longitude:longitude
							// 					  }
							// 					  if(addressData){
							// 							if(addressData.province)this.province = addressData.province;
							// 							if(addressData.city)this.city = addressData.city;
							// 							if(addressData.district)this.area = addressData.district; 

							// 							console.log("this.province2 = " + this.province);
							// 							console.log("this.city2 = " + this.city);
							// 							console.log("this.area2 = " + this.area);
							// 					  }
							// 					  uni.setStorageSync('addressData', JSON.stringify(addressData));/*全局缓存相关的数据*/ 
							// 				}
							// 		  }); 
						}
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.cu-form-group uni-picker::after {
		display: none;
	}

	::v-deep .cu-form-group uni-picker {
		padding-right: 0;
	}

	.image-center {
		display: flex;
		justify-content: center
	}

	.upload {
		padding: 20rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #F7F7F7;
	}

	.upload-box {
		height: 240rpx;
		max-height: 300rpx;
	}

	.upload-item {
		display: flex;
		flex-direction: column;
		align-content: center;
		align-items: center;
		justify-items: center;
		justify-content: center;
		height: 100%;
		border: 1rpx solid #dddddd;
		background-color: #F7F7F7;
	}

	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.grid {
		position: relative;

		.tag {
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			z-index: 3;
			width: 40rpx;
			height: 40rpx;
			border-radius: 5500rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			text-align: center;
			overflow: hidden;
			background-color: #e6162c;
		}
	}
</style>